package com.dmai.capacity.platform.oauth.service.impl;

import javax.annotation.Resource;

import com.dmai.capacity.platform.common.service.IUserBaseService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.stereotype.Service;

import com.dmai.capacity.platform.common.constant.SecurityConstants;
import com.dmai.capacity.platform.common.model.LoginAppUser;
import com.dmai.capacity.platform.oauth.service.DefaultUserDetailsService;

import lombok.extern.slf4j.Slf4j;

/**
 * 默认后台用户类型插件
 */
@Slf4j
@Service
public class UserDetailServiceImpl implements DefaultUserDetailsService {
    private static final String ACCOUNT_TYPE = SecurityConstants.DEF_ACCOUNT_TYPE;

    @Resource
    private IUserBaseService userService;

    @Override
    public boolean supports(String accountType) {
        return ACCOUNT_TYPE.equals(accountType);
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        LoginAppUser loginAppUser = userService.findByUsername(username);
        if (loginAppUser == null || !loginAppUser.getEnabled() || loginAppUser.getDeleted()) {
            // 禁用的，已删除的都登录失败
            return null;
        }
        return loginAppUser;
    }

    @Override
    public SocialUserDetails loadUserByUserId(Long userId) throws UsernameNotFoundException {
        LoginAppUser loginAppUser = userService.findByUserId(userId);
        return loginAppUser;
    }

    @Override
    public SocialUserDetails loadUserByOpenId(String openId) {
        LoginAppUser loginAppUser = userService.findByOpenId(openId);
        return loginAppUser;
    }

    @Override
    public UserDetails loadUserByMobile(String mobile) {
        LoginAppUser loginAppUser = userService.findByMobile(mobile);
        return loginAppUser;
    }


}
